package com.spit.fammo.viewmodel

import android.util.Log
import android.view.View
import androidx.databinding.ObservableInt
import androidx.fragment.app.Fragment
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.spit.amoeba.base.MyBaseViewModel
import com.spit.fammo.R
import com.spit.fammo.api.UIHelper
import com.spit.fammo.bean.BaseResponseBean
import com.spit.fammo.bean.DataBean
import com.spit.fammo.bean.db.ListingBean
import com.spit.fammo.ext.LISTING_CATEGORY_TYPE
import com.spit.fammo.ext.showMessage
import com.spit.fammo.network.apiService
import com.spit.fammo.util.CacheUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.base.appContext
import me.hgj.jetpackmvvm.callback.databind.BooleanObservableField
import me.hgj.jetpackmvvm.callback.databind.StringObservableField
import me.hgj.jetpackmvvm.ext.requestNoCheck
import me.hgj.jetpackmvvm.state.ResultState

/**
 * @Author nike
 * @Date 2023/7/5 14:55
 * @Description
 */
class LoginModel: MyBaseViewModel() {

    //用户名
    var username = StringObservableField()

    var versionName = StringObservableField(AppUtils.getAppName() + "：v" + AppUtils.getAppVersionName())

    //密码(登录注册界面)
    var password = StringObservableField()

    //是否显示明文密码（登录注册界面）
    var isShowPwd = BooleanObservableField()

    private var isLocation: Boolean = false
    private var isCategory: Boolean = false
    private var userBean: DataBean? = null

    //用户名清除按钮是否显示   不要在 xml 中写逻辑 所以逻辑判断放在这里
    var clearVisible = object :ObservableInt(username){
        override fun get(): Int {
            return if(username.get().isEmpty()){
                View.GONE
            }else{
                View.VISIBLE
            }
        }
    }

    //密码显示按钮是否显示   不要在 xml 中写逻辑 所以逻辑判断放在这里
    var passwordVisible = object : ObservableInt(password){
        override fun get(): Int {
            return if(password.get().isEmpty()){
                View.GONE
            }else{
                View.VISIBLE
            }
        }
    }



    //方式1  自动脱壳过滤处理请求结果，判断结果是否成功
    var loginResult = MutableLiveData<ResultState<BaseResponseBean<DataBean>>>()
//
    //方式2  不用框架帮脱壳，判断结果是否成功
//    var loginResult = MutableLiveData<ResultState<ApiResponse<UserInfo>>>()

    fun login(username: String, password: String, frg: Fragment) {
        /*requestNoCheck({apiService.CheckLogin(username, password)},{
            it.forEach { bean ->
                when (bean.Status) {
                    0 -> {
                        frg.showMessage(frg.getString(R.string.username_not_exist))
                    }
                    1 -> {
                        frg.showMessage(frg.getString(R.string.incorrect_credential))
                    }
                    else -> {
                        userList(username)
                    }
                }
            }
        },{
            //请求失败 网络异常回调在这里
            loadingChange.dismissDialog
            ToastUtils.showShort(it.throwable!!.message)
            LogUtils.e(it.throwable, it.throwable!!.message)
        }, false)*/


        requestNoCheck({apiService.CheckLogin(username.trim(), password.trim())},{
            when (it.Status) {
                0 -> {
                    frg.showMessage(frg.getString(R.string.username_not_exist))
                }
                1 -> {
                    frg.showMessage(frg.getString(R.string.incorrect_credential))
                }
                else -> {
                    CacheUtil.setToken(it.token)
                    userList(username, password)
                }
            }
        },{
            //请求失败 网络异常回调在这里
            loadingChange.dismissDialog
            ToastUtils.showShort(it.throwable!!.message)
            LogUtils.e(it.throwable, it.throwable!!.message)
        }, false)

    }

    private fun userList(username: String, password: String) {
        requestNoCheck({apiService.userList(username)},{
            val data = it.data
            if (!data.isNullOrEmpty()){
                var bean = data.find { it.LoginID?.lowercase() == username.lowercase() }
                if (bean != null){
                    bean.Password = password
                    userBean = bean
                    CacheUtil.setUser(userBean)
                    UIHelper.startMainAct()
                    ActivityUtils.finishAllActivities()
                   /* viewModelScope.launch(Dispatchers.IO) {
                        listingDao.deleteAll()
                        onlisting(LISTING_CATEGORY_TYPE, bean)
                        onlisting(LISTING_LOCATION_TYPE, bean)
                    }*/
                }
            }
        },{
            //请求失败 网络异常回调在这里
            loadingChange.dismissDialog
            ToastUtils.showShort(it.throwable!!.message)
            LogUtils.e(it.throwable, it.throwable!!.message)
        }, true, loadingMessage = "")
    }

    private fun onlisting(type: Int, userBean: DataBean) {
        requestNoCheck({apiService.listing(type, "")},{
            viewModelScope.launch(Dispatchers.IO) {
                if (it.size == 0){
                    if (type == LISTING_CATEGORY_TYPE){
                        isCategory = true
                    }else{
                        isLocation = true
                    }
                    startMainAct()
                }else{
                    it?.forEachIndexed { index, bean ->
                        bean.fatherrono = userBean.userid
                        bean.type = type
                        listingDao.add(bean)
                        onlisting2(type, bean, index == it.size - 1 )
                    }
                }
            }
        },{
            //请求失败 网络异常回调在这里
            loadingChange.dismissDialog
            ToastUtils.showShort(it.throwable!!.message)
            LogUtils.e(it.throwable, it.throwable!!.message)
            Log.e("-------", it.throwable.toString())
        }, false)
    }

    private fun onlisting2(type: Int, oneParentBean: ListingBean, isOneAll: Boolean) {
        requestNoCheck({apiService.listing(type, oneParentBean.rono)},{
            viewModelScope.launch(Dispatchers.IO) {
                if (isOneAll && it.size == 0){
                    if (type == LISTING_CATEGORY_TYPE){
                        isCategory = true
                    }else{
                        isLocation = true
                    }
                    startMainAct()
                }else{
                    it?.forEachIndexed { index, bean ->
                        bean.type = type
                        listingDao.add(bean)
                        onlisting3(type, oneParentBean, isOneAll, bean, index == it.size - 1)
                    }
                }
            }
        },{
            //请求失败 网络异常回调在这里
            loadingChange.dismissDialog
            ToastUtils.showShort(it.throwable!!.message)
            LogUtils.e(it.throwable, it.throwable!!.message)
        }, false)
    }

    private fun onlisting3(type: Int, oneParentBean: ListingBean, isOneAll: Boolean, twoParentBean: ListingBean, isTwoAll: Boolean) {
        requestNoCheck({apiService.listing(type, twoParentBean.rono)},{
            viewModelScope.launch(Dispatchers.IO) {
                if (isOneAll && isTwoAll && it.size == 0){
                    if (type == LISTING_CATEGORY_TYPE){
                        isCategory = true
                    }else{
                        isLocation = true
                    }
                    startMainAct()
                }else{
                    it?.forEachIndexed { index, bean ->
                        bean.type = type
                        listingDao.add(bean)
                        if (isOneAll && isTwoAll && index == it.size - 1){
                            if (type == 0){
                                isCategory = true
                            }else{
                                isLocation = true
                            }
                            startMainAct()
                        }
                    }
                }
            }
        },{
            //请求失败 网络异常回调在这里
            loadingChange.dismissDialog
            ToastUtils.showShort(it.throwable!!.message)
            LogUtils.e(it.throwable, it.throwable!!.message)
        }, false)
    }

    private fun startMainAct() {
        if (isCategory && isLocation){
            CacheUtil.setUser(userBean)
            UIHelper.startMainAct()
            ActivityUtils.finishAllActivities()
        }
    }

}